package cc.vv.party.api;


import cc.vv.party.beans.model.Org
import cc.vv.party.beans.model.OrgAdmin
import cc.vv.party.beans.vo.*
import cc.vv.party.common.base.BaseController
import cc.vv.party.common.constants.StatusCode
import cc.vv.party.common.constants.SysConsts
import cc.vv.party.common.constants.enums.RoleType
import cc.vv.party.common.ext.toTree
import cc.vv.party.common.wrapper.PageWrapper
import cc.vv.party.common.wrapper.ResponseEntityWrapper
import cc.vv.party.exception.BizException
import cc.vv.party.logger.annotation.OperateLog
import cc.vv.party.service.*
import com.baomidou.mybatisplus.mapper.EntityWrapper
import commonx.core.content.transfer
import commonx.core.content.transferEntries
import io.swagger.annotations.Api
import io.swagger.annotations.ApiImplicitParam
import io.swagger.annotations.ApiImplicitParams
import io.swagger.annotations.ApiOperation
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController

/**
 * <p>
 * 组织机构 前端控制器
 * </p>
 *
 * @author Gyb
 * @since 2018-10-12
 */
@RestController
@RequestMapping("/api/org")
@Api(value = "组织机构相关", tags = ["组织机构相关客户端API"], description = "组织机构相关客户端API-客户端组织机构相关相关接口")
class OrgApi : BaseController() {

    @Autowired
    lateinit var orgService: OrgService

    @Autowired
    lateinit var orgAdminService: OrgAdminService

    @Autowired
    lateinit var societyOrgService: SocietyOrgService

    @Autowired
    lateinit var societyOrgDynamicService: SocietyOrgDynamicService

    @Autowired
    lateinit var communityActivityService: CommunityActivityService

    @ApiOperation("社区组织")
    @ApiImplicitParam(value = "社区id", name = "id", required = false)
    @GetMapping("/community-org")
    fun committeeDetail(@RequestParam(required = false) id: String?): ResponseEntityWrapper<CommunityVO> {
        val communityId = findCommunityId(id)
        return success(orgService.getCommunityAndChildrenById(communityId!!))
    }


    @ApiOperation("获取社会组织列表-分页")
    @ApiImplicitParams(
        value = [
            ApiImplicitParam(value = "当前页", name = "page"),
            ApiImplicitParam(value = "分页大小", name = "pageSize"),
            ApiImplicitParam(value = "社区id", name = "communityId")
        ]
    )
    @GetMapping("/society-org-list")
    fun societyOrgList(@RequestParam page: Int, @RequestParam pageSize: Int, @RequestParam communityId: String): ResponseEntityWrapper<PageWrapper<SocietyOrgVO>> {
        return success(societyOrgService.listPage(communityId, null, pageSize, page))
    }

    @ApiOperation("获取社会组织动态列表-分页")
    @ApiImplicitParams(
        value = [
            ApiImplicitParam(value = "当前页", name = "page"),
            ApiImplicitParam(value = "分页大小", name = "pageSize"),
            ApiImplicitParam(value = "社区id", name = "communityId")
        ]
    )
    @GetMapping("/society-org-dynamic-list")
    fun societyOrgDynamicList(@RequestParam page: Int, @RequestParam pageSize: Int, @RequestParam communityId: String): ResponseEntityWrapper<PageWrapper<SocietyOrgDynamicVO>> {
        return success(societyOrgDynamicService.listPageByCommunityId(communityId, pageSize, page))
    }

    @ApiOperation("网格列表")
    @ApiImplicitParam(value = "社区id", name = "communityId", required = false)
    @GetMapping("/grid-list")
    fun gridList(@RequestParam(required = false) communityId: String): ResponseEntityWrapper<MutableList<OrgVO>> {
        val id = findCommunityId(communityId)
        return success(orgService.getGridListByCommunityId(id!!))
    }

    @ApiOperation("楼栋党小组详情")
    @ApiImplicitParam(value = "楼栋党orgId", name = "orgId")
    @GetMapping("/building-info")
    fun buildingInfo(@RequestParam orgId: String): ResponseEntityWrapper<OrgVO> {
        return success(orgService.getOrgDetailById(orgId))
    }


    @ApiOperation("单元中心户详情")
    @ApiImplicitParam(value = "单元中心户orgId", name = "orgId")
    @GetMapping("/center-info")
    fun centerInfo(@RequestParam orgId: String): ResponseEntityWrapper<OrgVO> {
        return success(orgService.getOrgDetailById(orgId))
    }

    @ApiOperation("社区活动列表-分页")
    @ApiImplicitParams(
        value = [
            ApiImplicitParam(value = "当前页", name = "page", required = true),
            ApiImplicitParam(value = "分页大小", name = "pageSize", required = true),
            ApiImplicitParam(value = "社区id", name = "communityId", required = false)
        ]
    )
    @GetMapping("/community-activity-list")
    fun communityActivityList(@RequestParam page: Int, @RequestParam pageSize: Int, @RequestParam(required = false) communityId: String?): ResponseEntityWrapper<PageWrapper<CommunityActivityVO>> {
        val id = findCommunityId(communityId)
        return success(communityActivityService.listByCommunityId(id!!, pageSize, page))
    }

    @ApiOperation("社区活动详情")
    @ApiImplicitParam(value = "社区活动Id", name = "id")
    @GetMapping("/community-activity-detail")
    fun communityActivityDetail(@RequestParam id: String): ResponseEntityWrapper<CommunityActivityVO> {
        return success(communityActivityService.info(id))
    }

    @ApiOperation("组织查询-组织机构树")
    @GetMapping("/org-tree")
    fun orgTree(): ResponseEntityWrapper<OrgVO> {
        return success(orgService.getOrgList())
    }

    @ApiOperation("组织查询-组织机构详情")
    @ApiImplicitParam(value = "组织机构Id", name = "orgId", required = true)
    @GetMapping("/org-info")
    fun orgInfo(@RequestParam orgId: String): ResponseEntityWrapper<OrgVO> {
        return success(orgService.getOrgDetailById(orgId))
    }

    @ApiOperation(value = "获取某些类型的组织机构列表")
    @ApiImplicitParam(
        name = "type",
        value = "组织机构类型，可输入多个用','分割(0:社区，1:街道，2:社区，3:网格，4:单位，5:社会组织，6:楼栋党小组，7:党员，8:单元中心户，9:支部，10:街道联席会议，11:四支队伍，12:非公党建，13:社区大党委)"
    )
    @GetMapping("/org-list-by-type")
    fun orgListByType(@RequestParam type: List<Int>): ResponseEntityWrapper<List<OrgVO>> {
        return success(
            orgService.selectList(
                EntityWrapper<Org>().`in`(
                    "type",
                    type
                )
            ).transferEntries<OrgVO>() as List<OrgVO>
        )
    }

    @ApiOperation(value = "获取某一个层级上的组织结构树")
    @ApiImplicitParam(
        name = "type",
        value = "组织机构类型(0:社区，1:街道，2:社区，3:网格，4:单位，5:社会组织，6:楼栋党小组，7:党员，8:单元中心户，9:支部，10:街道联席会议，11:四支队伍，12:非公党建，13:社区大党委)"
    )
    @GetMapping("/org-tree-by-type")
    fun orgTreeByType(@RequestParam type: Int): ResponseEntityWrapper<OrgVO> {
        return success(
            (orgService.selectList(
                EntityWrapper<Org>().le(
                    "type",
                    type
                )
            ).transferEntries<OrgVO>() as List<OrgVO>).toTree()
        )
    }

    /**
     * 查找当前用户的所在社区
     */
    private fun findCommunityId(id: String?): String? {
        var communityId = id
        if (communityId.isNullOrEmpty()) {
            //查询当前所在社区
            communityId = getCurrentUserInfo().community
        }
        return communityId
    }

    @ApiOperation(value = "获取党组织机构列表", notes = "获取党组织机构列表")
    @ApiImplicitParams(
        value = [ApiImplicitParam(name = "type", value = "节点类型", required = false),
            ApiImplicitParam(name = "nodeId", value = "节点Id", required = false)]
    )
    @GetMapping("/party-node-list")
    fun partyNodeList(
        @RequestParam(required = false) type: String?,
        @RequestParam(required = false) nodeId: String?
    ): ResponseEntityWrapper<List<NodeVO>> {
        return success(orgService.findPartyNode(type, nodeId))
    }

    @ApiOperation(value = "获取指定父级下指定子集类型集合的组织列表")
    @ApiImplicitParams(
        value = [
            ApiImplicitParam(name = "parentId", value = "父级编号", required = true),
            ApiImplicitParam(
                name = "types",
                value = "组织机构类型，可输入多个用','分割(0:社区，1:街道，2:社区，3:网格，4:单位，5:社会组织，6:楼栋党小组，7:党员，8:单元中心户)",
                dataType = "Array",
                required = true
            )
        ]
    )
    @GetMapping("/child-type-list")
    fun findChildTypesList(@RequestParam parentId: String, @RequestParam types: List<Int>): ResponseEntityWrapper<List<OrgVO>> {
        var list = orgService.selectList(EntityWrapper<Org>().where("p_id = {0}", parentId).and().`in`("type", types))
            ?: emptyList()
        return success(list.transferEntries<OrgVO>() as ArrayList)
    }

    @ApiOperation(value = "获取指定社区下的单位列表")
    @ApiImplicitParams(
        value = [
            ApiImplicitParam(name = "communityId", value = "社区编号", required = true)
        ]
    )
    @GetMapping("/unit-list")
    fun findUnitList(@RequestParam communityId: String): ResponseEntityWrapper<List<OrgVO>> {
//        val currentRole =
//            getCurrentUserRole()
//                    .find { it.type == RoleType.SECTION_ADMIN || it.type == RoleType.UNIT_ADMIN }
//                ?: throw BizException(StatusCode.FORBIDDEN.statusCode, "只能社区和单位管理员可以进行操作")
        val result =
//            when {
//                currentRole.type == RoleType.SECTION_ADMIN ->
                    orgService.selectList(
                    EntityWrapper<Org>().where("p_id = {0}", communityId).and().eq("type", "4")
                ) ?: emptyList()
//                currentRole.type == RoleType.UNIT_ADMIN -> {
//                    val orgAdmin =
//                        orgAdminService.selectOne(EntityWrapper<OrgAdmin>().eq("user_account", getCurrentUserAccount()))
//                    orgService.selectList(
//                        EntityWrapper<Org>().where("id = {0}", orgAdmin.orgId).and().eq(
//                            "type",
//                            "4"
//                        ).eq("p_id", communityId)
//                    )
//                }
//                else -> throw BizException(StatusCode.FORBIDDEN.statusCode, "只能社区和单位管理员可以进行操作")
//            }

        return success(result.transferEntries<OrgVO>() as ArrayList)
    }

    @ApiOperation(value = "组织机构管理-组织机构列表", notes = "组织机构列表")
    @GetMapping("/list-with-auth")
    @OperateLog(content = "查看组织结构列表")
    fun orgListWithAuth(): ResponseEntityWrapper<OrgVO> {
        return success(orgService.getManagedOrgList(getCurrentUserAccount()))
    }
}
